package com.linked.basemanage.dictionary.controller;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.linked.basemanage.dictionary.bean.po.DictoryInfoPO;
import com.linked.basemanage.dictionary.service.IDictionaryHandleService;
import com.linked.universal.common.Result;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * @author :dbq
 * @date : 2023/1/13 11:23
 * @description : desc
 */
@RestController
@RequestMapping("dictionaryhandle")
@Slf4j
public class DictionaryHandleController {

    private final static String dictionary = "DICTIONARY";

    private final IDictionaryHandleService dictionaryHandleService;

    private final ObjectMapper mapper;

    private final RedisTemplate redisTemplate;

    @Autowired
    public DictionaryHandleController(IDictionaryHandleService dictionaryHandleService, ObjectMapper mapper, RedisTemplate redisTemplate) {
        this.dictionaryHandleService = dictionaryHandleService;
        this.mapper = mapper;
        this.redisTemplate = redisTemplate;
    }

    @PostMapping("saveDictoryInfo")
    Result saveDictoryInfo(@NonNull @RequestBody DictoryInfoPO param) throws Exception {
        if (log.isInfoEnabled()) {
            log.info("保存字典接口，入参:{}", mapper.writeValueAsString(param));
        }
        boolean ret = dictionaryHandleService.saveDictoryInfo(param);
        if (ret) {
            redisTemplate.delete( param.getUseLocation() + "-" + param.getDictionaryCode());
            return Result.ok(true, "保存成功");
        } else {
            return Result.ok(false, "保存失败");
        }
    }

    @PostMapping("queryDictoryList")
    Result queryDictoryList(@NonNull String useLocation, @NonNull String dictionaryCode) throws Exception {
        String redisKey = useLocation + "-" + dictionaryCode;
        if (redisTemplate.hasKey(redisKey)) {
            String jsonDictorys = (String) redisTemplate.opsForValue().get(redisKey);
            return Result.success(mapper.readValue(jsonDictorys, new TypeReference<List<DictoryInfoPO>>() {
            }));
        }
        List<DictoryInfoPO> res = dictionaryHandleService.queryDictoryList(useLocation, dictionaryCode);
        if (CollectionUtils.isEmpty(res)) {
            return Result.ok(false, "未查询到数据");
        } else {
            redisTemplate.opsForValue().set(redisKey, mapper.writeValueAsString(res));
            return Result.success(res);
        }
    }
}
